import { stadium_fields } from "../../utils/dataset/db_fields";
import { sport_data } from "../../utils/dataset/db_data";

Page({
  data: {
    stadiumId: '',  // 用于编辑资料
    stadium_name: '',
    stadium_phone: '',
    appointment_period: null,
    stadium_addr: '',
    stadium_geo: null,
    stadium_desc: '',
    start_time: '00:00',
    end_time: '23:59',
    employer_id: '',
    employer: { real_name: '', idx: 0 },
    employee_ids: [],
    sport_ids: [],
    actAction: '',
    sportSelected: [],
    employeeSelected: [],
    fig_urls: [],
    imgList: [],
    sportList: sport_data.map(o => { return { _id: o._id, label: o.sport_name } }),
    employerList: [],
    employeeList: [],
    submitLock: 0,
  },
  async onLoad(options) {
    if (options.stadiumId) {
      this.setData({ stadiumId: options.stadiumId });
      await this.loadStadiumData(options.stadiumId);
    }
    // 加载用户资料，必须等球场信息加载完毕，获取 stadiumId
    this.loadUserData(1);
    this.loadUserData(2);
  },
  async loadUserData(role_id) {
    let resList = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_user',
        data: {
          funcName: 'query',
          searchText: '',
          searchData: { role_id: role_id }
        },
        success: (r) => resolve(r.result),
      });
    });
    resList = resList.map(o => {
      return {
        _id: o._id,
        label: o.real_name || o.username
      };
    });
    if (role_id == 1) {
      this.setData({ employerList: resList });
      // 雇佣者
      if (!this.data.stadiumId) return;
      const employer_id = this.data.employer_id;
      console.log(employer_id);
      console.log(resList);
      for (let i = 0; i < resList.length; i++) {
        if (resList[i]._id == employer_id) {
          this.setData({ employer: { real_name: resList[i].label, idx: i } })
          break;
        }
      }
    } else {
      this.setData({ employeeList: resList });
      // 被雇佣者已选
      if (!this.data.stadiumId) return;
      const _employeeSelected = [];
      const employee_ids = this.data.employee_ids;
      resList.forEach((o, i) => {
        if (employee_ids.indexOf(o._id) + 1) {
          _employeeSelected.push(String(i));
        }
      })
      this.setData({ employeeSelected: _employeeSelected })
    }
  },
  async loadStadiumData(stadium_id) {
    let resList = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_stadium',
        data: {
          funcName: 'query',
          searchText: '',
          searchData: { _id: stadium_id }
        },
        success: (r) => resolve(r.result),
      });
    });
    if (resList.length > 0) {
      const res = resList[0];
      res.stadium_geo = { longitude: res.stadium_geo.coordinates[0], latitude: res.stadium_geo.coordinates[1] };
      let _data = {};
      stadium_fields.forEach(k => _data[k] = res[k]);
      this.setData(_data);
      // 运动已选
      const _sportSelected = [];
      this.data.sportList.forEach((o, i) => {
        if (res.sport_ids.indexOf(o._id) + 1) {
          _sportSelected.push(String(i));
        }
      })
      this.setData({ sportSelected: _sportSelected })
    }
  },
  onSelectLocation() {
    let self = this;
    wx.chooseLocation({
      success(res) {
        self.setData({
          stadium_addr: res.address || '未知',
          stadium_geo: { longitude: res.longitude, latitude: res.latitude }
        })
      }
    })
  },
  async onSubmit() {
    this.setData({ submitLock: 1 });
    const validated = stadium_fields.every(k => {
      const val = this.data[k];
      if (['stadium_geo', 'stadium_desc'].indexOf(k) + 1) return 1;
      if (['sport_ids', 'employee_ids'].indexOf(k) + 1) return (val.length > 0);
      if (k == 'stadium_phone') return (/^1[3456789]\d{9}$/.test(val));
      if (val) return 1;
      return 0;
    })
    const docData = {}; // addData or updData
    if (validated) {
      stadium_fields.forEach(k => docData[k] = this.data[k])
      console.log(docData);
      let _data = {};
      if (this.data.stadiumId) {
        _data.funcName = 'update';
        _data.stadium_id = this.data.stadiumId;
        _data.updData = docData;
      } else {
        _data.funcName = 'insert';
        docData._id = String().nanoid();
        _data.addData = docData;
      }
      const res = await new Promise(resolve => {
        wx.cloud.callFunction({
          name: 'db_stadium',
          data: _data,
          success: (r) => resolve(r.result),
          fail: () => resolve()
        });
      })
      console.log(res);
      if ((this.data.stadiumId && !res) || (!this.data.stadiumId && res.errMsg)) {
        wx.showToast({ title: !res ? '操作失败，未知错误' : res.errMsg, icon: 'none' });
      } else {
        wx.showToast({ title: '操作成功' });
        setTimeout(() => { wx.navigateBack(); this.setData({ submitLock: 0 }) }, 200);
      }
    } else {
      wx.showToast({
        title: '填写不完整或不符合规范',
        icon: 'none',
      })
      this.setData({ submitLock: 0 })
    }
  },
  onSelectSport(ev) {
    this.setData({ sport_ids: ev.detail });
  },
  onChangeTime(ev) {
    const timeStr = ev.detail.value;
    if (ev.currentTarget.dataset.time == 'start_time') {
      this.setData({ start_time: timeStr });
    }
    if (ev.currentTarget.dataset.time == 'end_time' || timeStr > this.data.end_time) {
      this.setData({ end_time: timeStr });
    }
  },
  onSelectEmployer(ev) {
    const idx = ev.detail.value;
    const user = this.data.employerList[idx];
    this.setData({ employer_id: user._id, employer: { real_name: user.label, idx: idx } });
  },
  onShowAction(ev) {
    const dataName = ev.currentTarget.dataset.name;
    this.setData({ actAction: dataName });
  },
  onHideAction(ev) {
    const seleced = this.selectComponent('#my-checkbox');
    const actAction = this.data.actAction;
    if (actAction === 'sport') {
      this.setData({
        actAction: '',
        sportSelected: seleced,
        sport_ids: this.data.sportList.filter((o, i) => (String(i) in seleced)).map(o => o._id)
      });
    } else if (actAction === 'employee') {
      this.setData({
        actAction: '',
        employeeSelected: seleced,
        employee_ids: this.data.employeeList.filter((o, i) => (String(i) in seleced)).map(o => o._id)
      })
    }
  },
})